# ==============================
# _*_ coding:utf-8 _*_
# _*_ by:zizle     _*_
# _*_ at:20230423  _*_
# ==============================

from fastapi import APIRouter, Query
from db_utils import BaseDatabaseConnection
from utils import datetime_utils
from response import APIResponse


class SymbolCandle:
    def __init__(self, code, start, end):
        self.code = code
        self.start = datetime_utils.auth_yyyymmdd(start, obj=True)
        self.end = datetime_utils.auth_yyyymmdd(end, obj=True)
        assert self.start
        assert self.end

    def symbol_candle(self):
        start_date = datetime_utils.to_yyyy_mm_dd(self.start)
        end_date = datetime_utils.to_yyyy_mm_dd(self.end)
        with BaseDatabaseConnection() as conn:
            conn.cursor.execute("""
                SELECT code,`time`,`open`,`close`,`low`,`high` FROM quote_candle_daily
                WHERE code=%s AND time>=%s AND time<=%s ORDER BY time;
            """, [self.code, start_date, end_date])
            results = list(conn.cursor.fetchall())
        for row in results:
            for k in ['open', 'close', 'low', 'high']:
                row[k] = round(row[k], 2)
        res_data = {
            'symbol': self.code,
            'result': results
        }
        return APIResponse.success(data=res_data)


time_sequence_api = APIRouter()


# 获取蜡烛图数据
@time_sequence_api.get('/candle/')
def symbol_candle(symbol: str = Query(...), start: str = Query(...), end: str = Query(...)):
    return SymbolCandle(code=symbol, start=start, end=end).symbol_candle()
